package com.loe.camera;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.util.List;

import androidx.core.content.FileProvider;

public class CameraUriUtil
{
    @Deprecated
    public static Uri fileToUri(Context context, File file)
    {
        String filePath = file.getAbsolutePath();

        Uri uri = null;

        try
        {
            Cursor cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{file.getName()}, null);
            if (cursor != null && cursor.moveToFirst())
            {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);

                if (uri != null)
                {
                    return uri;
                }
            }

            cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null);
            if (cursor != null && cursor.moveToFirst())
            {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);

                if (uri != null)
                {
                    return uri;
                }
            }
        } catch (Exception e)
        {
        }


        try
        {
            if (file.exists())
            {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                if (uri != null)
                {
                    return uri;
                }
            }
        } catch (Exception e)
        {
        }


        uri = Uri.fromFile(file);

        return uri;
    }

    public static Uri getProviderUri(Context context, File file)
    {
        // 7.0+ 以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            return FileProvider.getUriForFile(context, context.getPackageName() + ".camerafileprovider", file);
        }
        else
        {
            return Uri.fromFile(file);
        }
    }

    @SuppressLint("NewApi")
    public static String getUriPath(final Context context, final Uri uri)
    {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        String scheme = uri.getScheme();
        String path = null;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
        {
            try
            {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri))
                {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type))
                    {
                        path =  Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri))
                {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    path = getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri))
                {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type))
                    {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    }
                    else if ("video".equals(type))
                    {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    }
                    else if ("audio".equals(type))
                    {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};

                    path = getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }catch (Exception e)
            {
                Log.e("runtime", e.toString());
            }
        }
        if ("content".equalsIgnoreCase(scheme))
        {
            try
            {
                if (isQQMediaDocument(uri))
                {
                    String paths = uri.getPath();
                    File fileDir = Environment.getExternalStorageDirectory();
                    String p = paths.substring(paths.indexOf("/", 1));
                    File file = new File(fileDir, p);
                    path = file.exists() ? file.toString() : null;
                }
            }catch (Exception e)
            {
                Log.e("runtime", e.toString());
            }
            if (isGooglePhotosUri(uri))
            {
                return uri.getLastPathSegment();
            }
        }
        // MediaStore (and general)
        if(path == null)
        {
            try
            {
                path = getDataColumn(context, uri, null, null);
            }catch (Exception e)
            {
                Log.e("runtime", e.toString());
            }
        }
        // File
        if(path == null)
        {
            try
            {
                path = uri.getPath();
            }catch (Exception e)
            {
                Log.e("runtime", e.toString());
            }
        }

        return path;
    }

    public static boolean isQQMediaDocument(Uri uri)
    {
        return "com.tencent.mtt.fileprovider".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri)
    {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
    {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try
        {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst())
            {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally
        {
            if (cursor != null)
            {
                cursor.close();
            }
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri)
    {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri)
    {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri)
    {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static void grantPermissionFix(Context context, Intent intent, Uri uri)
    {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resolveInfos)
        {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setAction(null);
            intent.setComponent(new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name));
            break;
        }
    }

}